//
//  UserCenterViewController.m
//  jinneng
//
//  Created by mac on 2020/7/31.
//  Copyright © 2020 jznrj. All rights reserved.
//

#import "UserCenterViewController.h"
#import "SafeTrainingViewController.h"
#import "DaliyTrainingViewController.h"
#import "TrainingClassViewController.h"
#import "LoginViewController.h"
#import "ChangePwdViewController.h"
#import <WKWebViewJavascriptBridge.h>
#import "ScanCodeViewController.h"
#import "PointViewControllerViewController.h"
#import "UserInfoViewController.h"
#import "UserCertificateViewController.h"
#import "UserDossierViewController.h"
@interface UserCenterViewController ()
@property(nonatomic,strong) JznWebView *titleView;
@property(nonatomic) int page;
@property(nonatomic,strong) NSString *module;
@property(nonatomic,strong) NSString * trade;
@property(nonatomic) CGRect frame;
@property(nonatomic,strong) ChangePwdViewController *changePwdViewController;
@property(nonatomic, strong) WKWebViewJavascriptBridge *titleBridge;
@end

@implementation UserCenterViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.title = @"个人中心";
//    UINavigationBar * bar = self.navigationController.navigationBar;
//    UIImage *bgImage = [ColorUtil navigationBarColor:[ColorUtil titleColor] BarSize:bar.frame alphe:1.0];
//    [bar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];
//    [bar setTintColor:[UIColor whiteColor]];
//    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]}forState:UIControlStateNormal];
//    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,nil]];
//    
//    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
//    
//    self.tabBarController.tabBar.frame = CGRectMake(0, 0, 0, 0);
//     self.tabBarController.tabBar.hidden = YES;
    _frame = self.tabBarController.tabBar.frame;
    [self initView];
    [self registerNativeFunctions];
}

-(void) viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden =YES;
    self.tabBarController.tabBar.hidden = NO;
    self.tabBarController.tabBar.frame = _frame;
}
-(void) viewDidAppear:(BOOL)animated{
   // self.navigationController.navigationBar.hidden =YES;
//    self.tabBarController.tabBar.hidden = NO;
//    self.tabBarController.tabBar.frame = _frame;
    
    [self requestPoint];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changePwd:) name:@"changePwd" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(removeChangeView) name:@"removeChangeView" object:nil];
}
-(void) viewDidDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"changePwd" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"removeChangeView" object:nil];
}
-(void) functionControlClick{
    _changePwdViewController=[[ChangePwdViewController alloc]init];
    [self addChildViewController:_changePwdViewController];
    [self.view addSubview:_changePwdViewController.view];
    [_changePwdViewController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(-40*LSCALE);
        make.bottom.equalTo(self.view);
    }];
}

-(void) initView{
    CGRect statusFrame = [[UIApplication sharedApplication] statusBarFrame];
    self.titleView  = [[JznWebView alloc]initWithFrame:_frame];
    [self.view addSubview:self.titleView];
    [self.titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(self.titleHeight+statusFrame.size.height);
        make.width.left.equalTo(self.view);
        make.top.equalTo(self.view).offset(-(5+statusFrame.size.height));
    }];
    NSLog(@"frame:%f",statusFrame.size.height);
    if(statusFrame.size.height<44){
        [self.titleView loadLocalFile:@"/ios_jinneng/jinnengTitle_new_small" type:@"html"];
    }else{
        [self.titleView loadLocalFile:@"/ios_jinneng/jinnengTitle_new" type:@"html"];
    }
    
    [self.view addSubview:self.jznWebView];
    [self.jznWebView mas_makeConstraints:^(MASConstraintMaker *make) {
         make.left.right.equalTo(self.view);
         make.top.equalTo(self.view).offset(self.titleHeight);
         if (@available(iOS 11.0, *)) {

             make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
         } else {
             make.bottom.equalTo(self.view);
         }
     }];
     self.view.backgroundColor = [UIColor whiteColor];
    self.jznWebView.scrollView.bounces = NO;
    [self.jznWebView loadLocalFile:@"/ios_jinneng/user_center" type:@"html"];
    self.titleBridge = [WKWebViewJavascriptBridge bridgeForWebView:self.titleView];
    [self.titleBridge setWebViewDelegate:self];


}

- (void)registerNativeFunctions {

    [self.webViewBridge registerHandler:@"toUserInfo" handler:^(id data, WVJBResponseCallback responseCallback) {
        dispatch_async(dispatch_get_main_queue(), ^(){
            UserInfoViewController *vc = [[UserInfoViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        });
    }];
    
    [self.webViewBridge registerHandler:@"toUserCertificate" handler:^(id data, WVJBResponseCallback responseCallback) {
           dispatch_async(dispatch_get_main_queue(), ^(){
               UserCertificateViewController *vc = [[UserCertificateViewController alloc]init];
               [self.navigationController pushViewController:vc animated:YES];
           });
       }];
    
    [self.webViewBridge registerHandler:@"toUserDossier" handler:^(id data, WVJBResponseCallback responseCallback) {
             dispatch_async(dispatch_get_main_queue(), ^(){
                 UserDossierViewController *vc = [[UserDossierViewController alloc]init];
                 [self.navigationController pushViewController:vc animated:YES];
             });
         }];
    
    [self.webViewBridge registerHandler:@"toUserDossier" handler:^(id data, WVJBResponseCallback responseCallback) {
          dispatch_async(dispatch_get_main_queue(), ^(){
              UserDossierViewController *vc = [[UserDossierViewController alloc]init];
              [self.navigationController pushViewController:vc animated:YES];
          });
      }];
    [self.webViewBridge registerHandler:@"changePwd" handler:^(id data, WVJBResponseCallback responseCallback) {
       dispatch_async(dispatch_get_main_queue(), ^(){
            [self functionControlClick];
        });
    }];
    
    [self.webViewBridge registerHandler:@"toTrainingClass" handler:^(id data, WVJBResponseCallback responseCallback) {
       dispatch_async(dispatch_get_main_queue(), ^(){
           TrainingClassViewController *vc = [[TrainingClassViewController alloc]init];
           [self.navigationController pushViewController:vc animated:YES];
       });
    }];
    
    [self.webViewBridge registerHandler:@"toDaliy" handler:^(id data, WVJBResponseCallback responseCallback) {
       dispatch_async(dispatch_get_main_queue(), ^(){
            DaliyTrainingViewController *vc = [[DaliyTrainingViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        });
    }];
    
    [self.webViewBridge registerHandler:@"toSafe" handler:^(id data, WVJBResponseCallback responseCallback) {
       dispatch_async(dispatch_get_main_queue(), ^(){
            SafeTrainingViewController *vc = [[SafeTrainingViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        });
    }];
    
    [self.webViewBridge registerHandler:@"logOut" handler:^(id data, WVJBResponseCallback responseCallback) {
        dispatch_async(dispatch_get_main_queue(), ^(){
            [self logout];
        });
    }];
    
    [self.webViewBridge registerHandler:@"toScan" handler:^(id data, WVJBResponseCallback responseCallback) {
         dispatch_async(dispatch_get_main_queue(), ^(){
             ScanCodeViewController *learnNewsViewController = [[ScanCodeViewController alloc]init];
             self.hidesBottomBarWhenPushed = YES;
             [self.navigationController pushViewController:learnNewsViewController animated:YES];
         });
      }];
    
    [self.titleBridge registerHandler:@"toPoint" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        dispatch_async(dispatch_get_main_queue(), ^(){

            PointViewControllerViewController *vc = [[PointViewControllerViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        });
        
    }];
    
    [self.titleBridge registerHandler:@"toScan" handler:^(id data, WVJBResponseCallback responseCallback) {
          
          dispatch_async(dispatch_get_main_queue(), ^(){
              NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
              if ([userDefault objectForKey:@"account"] == nil) {
                  LoginViewController *controller = [[LoginViewController alloc]init];
                  controller.tabIndex = 3;
                  controller.modalPresentationStyle = UIModalPresentationFullScreen;
                  [self presentModalViewController:controller animated:YES ];
                  return;
              }else{
                  ScanCodeViewController *learnNewsViewController = [[ScanCodeViewController alloc]init];
                  self.hidesBottomBarWhenPushed = YES;
                  [self.navigationController pushViewController:learnNewsViewController animated:YES];
              }
          });
          
      }];
}

-(void) logout{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setObject:nil forKey:@"account"];
    [userDefault setObject:nil forKey:@"pwd"];
    [userDefault setObject:nil forKey:@"token"];
    [userDefault setObject:nil forKey:@"userInfo"];
    LoginViewController *login = [[LoginViewController alloc]init];
    [UIApplication sharedApplication].delegate.window.rootViewController = login;
}

-(void) requestPoint{
    NSString *url = [NSString stringWithFormat:@"%@/userRank/findUserScore",[URLUtil hostName]];
    NSDictionary *params = @{@"userId":[NSString stringWithFormat:@"%d",self.loginDto.userId]};
    [JZNRequestUtil requestUrl:url requestParams:params success:^(DataResult *dataResult) {
        if(dataResult.code == 0){
            NSString *js = [NSString stringWithFormat:@"getPoint(%@)",dataResult.data];
            [self.titleView evaluateJavaScript:js completionHandler:nil];
        }else {
        }
    } failure:^(NSError *error) {
        
    }];
    
    NSString *url1 = [NSString stringWithFormat:@"%@/userEntry/userLoginCount",[URLUtil hostName]];
    NSDictionary *params1 = @{};
    [JZNRequestUtil requestUrl:url1 requestParams:params1 success:^(DataResult *dataResult) {
        if(dataResult.code == 0){
            NSString *js = [NSString stringWithFormat:@"getUserCount(%@)",dataResult.data];
            [self.titleView evaluateJavaScript:js completionHandler:nil];
        }else {
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    self.loginDto = [LoginDto mj_objectWithKeyValues: [userDefault objectForKey: @"userInfo"]];
    
    NSString *userName = [NSString stringWithFormat:@"userNameInfo('%@')",self.loginDto.userName];
    [self.jznWebView evaluateJavaScript:userName completionHandler:^(id _Nullable data, NSError * _Nullable error) {
        
    }];
    
    NSString *companyName = [NSString stringWithFormat:@"userCompanyInfo('%@')",self.loginDto.businessCompanyName];
   // [self.jznWebView stringByEvaluatingJavaScriptFromString: companyName];
    [self.jznWebView evaluateJavaScript:companyName completionHandler:nil];
    
    [self requestPoint];
    
    NSString *js = [NSString stringWithFormat:@"getUserName('%@')",self.loginDto.userName];
    [self.titleView evaluateJavaScript:js completionHandler:nil];
    
    NSString *js1 = [NSString stringWithFormat:@"getCompanyName('%@')",self.loginDto.businessCompanyName];
    [self.titleView evaluateJavaScript:js1 completionHandler:nil];
}

-(void) changePwd:(NSNotification*)notification{
    NSString *url = [NSString stringWithFormat:@"%@/user/changePassword",[URLUtil hostName]];
    NSString *loginDtoJson = [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
    LoginDto *loginDto = [LoginDto mj_objectWithKeyValues:loginDtoJson];
    NSDictionary *dictionary = @{@"password":[notification userInfo][@"password"],@"userId":[NSString stringWithFormat:@"%d",loginDto.userId]};
    
    [JZNRequestUtil requestUrl:url requestParams:dictionary success:^(DataResult *dataResult) {
        if(dataResult.code == 0){
            [self removeChangeView];
            [[UIApplication sharedApplication].delegate.window makeToast:@"修改成功"];
            LoginViewController *login = [[LoginViewController alloc]init];
            [UIApplication sharedApplication].delegate.window.rootViewController = login;
        }else {
            [[UIApplication sharedApplication].delegate.window makeToast:dataResult.msg];
        }
    } failure:^(NSError *error) {
        
    }];
}

-(void) removeChangeView{
    [self.changePwdViewController.view removeFromSuperview];
}
- (void)tabBarController:(UITabBarController*) tabBarController didSelectViewController:(UIViewController*)viewController{
    if (self.tabBarController.tabBar.isHidden) {
        self.tabBarController.tabBar.hidden = NO;
        self.tabBarController.tabBar.frame = _frame;
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


